﻿using HealthcareSystem.API.Read.Application.Command.Team;
using HealthcareSystem.API.Read.DTO.Team;
using HealthcareSystem.Domain.BasicSettings.Team;
using MediatR;
using WeekExam.PassPort.ErrorCode;
using WeekExam.PassPort.Infrastructure.Interface;

namespace HealthcareSystem.API.Read.Application.CommandHandel.Team
{
    /// <summary>
    /// 请求处理机构（树形）
    /// </summary>
    public class InstitutionCommandHandler : IRequestHandler<InstitutionCommand, ApiResult<List<InstitutionDTO>>>
    {
        private readonly IBaseRepository<Institution> instRep;

        public InstitutionCommandHandler(IBaseRepository<Institution> instRep)
        {
            this.instRep = instRep;
        }

        public Task<ApiResult<List<InstitutionDTO>>> Handle(InstitutionCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<InstitutionDTO>> result=new ApiResult<List<InstitutionDTO>>();
            result.Code=ResultCode.Success;
            result.Message = ResultCode.Success.ToString();

            //查询机构
            var alllist=instRep.GetAll().ToList();
            result.Data = GetInst(0, alllist);

            return Task.FromResult(result);

        }
        /// <summary>
        /// 获取机构信息
        /// </summary>
        /// <param name="fid"></param>
        /// <param name="alllist"></param>
        /// <returns></returns>
        public List<InstitutionDTO> GetInst(int fid, List<Institution> alllist)
        {
            var toplist = alllist.Where(x => x.SuperiorInstitution == fid);
            List<InstitutionDTO> dto=new List<InstitutionDTO>();
            foreach (var inst in toplist)
            {
                dto.Add(new InstitutionDTO
                {
                    value = inst.InstitutionId,
                    label = inst.InstitutionName,
                    children = GetInst(inst.InstitutionId, alllist)
                });
            }
            return dto;
        }

    }
}
